import {
  JOIN_DRAW,
  LEAVE_DRAW,
  ROOM_DRAW,
  DRAW_NOW,
  DRAW_DOWN,
  DRAW_SYS
} from '../../const'

/**
  data: {
    user: {
      userid: 1,
      username: string
    },
    room: {
      roomid: 1,
      roomname: string
    }
  }
 */

const joinDraw = (io, socket, opts, data) => {
  const { user, room } = data
  const { roomid, roomname } = room
  const { userid, username } = user
  const ROOM_ID = `${ROOM_DRAW}_${roomid}`
  let { drawUsers, drawCount } = opts
  socket.name = userid
  if (!(userid in drawUsers)) {
    drawUsers[userid] = username
    drawCount++
  }
  // 用户加入房间
  socket.join(ROOM_ID)
  console.log(`加入了[${roomid}-${roomname}]绘画房间`)
  // 对房间内的用户发送消息 包括自己
  io.sockets.in(ROOM_ID).emit(DRAW_SYS, {
    users: drawUsers,
    count: drawCount,
    message: `Ping! ${username} 加入了绘画房间`
  })
  // 广播 不包括自己
  // socket.broadcast.to(ROOM_DRAW).emit('event_name', data)
  console.log(`${username}加入了绘画房间`)
}

const leaveDraw = (io, socket, opts, data) => {
  const { room } = data
  const { roomid, roomname } = room
  const ROOM_ID = `${ROOM_DRAW}_${roomid}`
  const userid = socket.name
  let { drawUsers, drawCount } = opts
  // 用户离开房间
  socket.leave(ROOM_ID)
  if (userid in drawUsers) {
    const user = {
      userid,
      username: drawUsers[userid]
    }
    delete drawUsers[userid]
    drawCount--
    // 向房间内所有人发送通知
    io.sockets.in(ROOM_DRAW).emit(DRAW_SYS, {
      users: drawUsers,
      count: drawCount,
      message: `Pong! ${user.username} 离开了绘画房间`
    })
    // 向此用户发送通知
    socket.emit('leaveyou', user + ' you are leave！')
  }
}

const starListener = (io, socket, opts) => {
  // 加入绘画房间
  socket.on(JOIN_DRAW, (data) => {
    joinDraw(io, socket, opts, data)
  })
  // 离开绘画房间
  socket.on(LEAVE_DRAW, (data) => {
    leaveDraw(io, socket, opts, data)
  })
  // 监听用户绘画
  socket.on(DRAW_NOW, (obj) => {
    io.emit(DRAW_NOW, obj)
  })
  socket.on(DRAW_DOWN, (obj) => {
    io.emit(DRAW_DOWN, obj)
  })
}

export default starListener
